<template>
	<view class="content">
		<view class="navbar">
			<up-navbar title="审批单据" leftIconColor="#fff" @leftClick="closeApprovePopup" :fixed="false" :autoBack="false"
				:safeAreaInsetTop="true">
			</up-navbar>
		</view>

		<view class="TabsBox">
			<m-scroll-tag @tabChange="changeTab" :tagsList="ApproveTabList" bgColor="#52b583">
			</m-scroll-tag>
		</view>

		<scroll-view v-show="currentIndex==0" class="scroll-Y" style="width: 100%;"
			:style="{height:scrollViewHeight+'px'}" scroll-y="true">
			<mApprovalShowByDeal :option="BaseScreenParm">
			</mApprovalShowByDeal>
		</scroll-view>


		<scroll-view v-show="currentIndex==1" class="scroll-Y" style="width: 100%;"
			:style="{height:scrollViewHeight+'px'}" scroll-y="true">
			<view class="scrollBottomBox1" style="height: 100%;">

				<uni-section title="文件上传" type="line" style="margin-top: 10px;">
					<view style="padding: 0 10px;">

						<cl-upload v-model="uploadFile_list"
							:listStyle="{columns: 4,padding:'6px',columnGap:'10px',rowGap:'10px'}" useBeforeDelete
							@beforeDelete="beforeDelete" cloudType="other" :action="uploadFile_action"
							@onSuccess="onSuccess"></cl-upload>

					</view>
				</uni-section>


				<uni-section title="输入审批建议" type="line" style="padding: 0 10px;">
					<up--textarea v-model="ApprovalContent" height="50" placeholder="请输入输入审批建议"></up--textarea>
				</uni-section>


			</view>
		</scroll-view>



		<view class="x-bc bottomBox" :style="uni.$utils.disposeSafeBottomFun()">
			<button @click="returnApproval" class="content_bottom_primary_plainBtn CommonBtnSize"
				:disabled="!enabledSubmitBtn" style="margin-right: 8px;">转交</button>
			<button @click="dealApproval(2)" class="content_bottom_danger_Btn CommonBtnSize"
				:disabled="!enabledSubmitBtn" style="margin-right: 8px;">拒绝</button>
			<button @click="dealApproval(1)" class="content_bottom_primary_Btn CommonBtnSize"
				:disabled="!enabledSubmitBtn">确认通过</button>
		</view>

		<!-- <up-toast ref="uToastRef"></up-toast> -->


	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed, reactive, nextTick, getCurrentInstance } from 'vue';
	import { onLoad, onUnload } from "@dcloudio/uni-app";
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	import mApprovalShowByDeal from '@/uni_modules/mc-ui/components/m-node-warp/components/m-approval-show-by-deal/m-approval-show-by-deal.vue';
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();



	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1] as any;
	const eventChannel = currentPage.getOpenerEventChannel();

	let BaseScreenParm = reactive<any>({});

	Object.assign(BaseScreenParm, mainStore.BaseScreenParm);

	// 关闭
	function closeApprovePopup(type = 'cancel', data : any = null) {
		hide(type, data);
	};
	function hide(type : any, data = null) {
		inventoryStore.st_comPageConfig.showFormApprove = true;
		setTimeout(() => {
			inventoryStore.st_comPageConfig.showFormApprove = false;
			uni.navigateBack({
				delta: 1,
				success() {
					eventChannel.emit(type, data);
				}
			})
		}, 100);
	}

	// tab数据
	let ApproveTabList = [
		{ name: '审批流程', value: 0 },
		{ name: '附件/备注', value: 1 },
	];
	// 选中索引
	let currentIndex = ref(0);
	// 切换Tab
	function changeTab(item : any) {
		currentIndex.value = item.Index;
	};

	const { windowHeight } = uni.$utils.getWindowInfo();
	let scrollViewHeight = ref(windowHeight * 0.8);

	async function getScrollHeight() {
		uni.createSelectorQuery().select('.navbar').boundingClientRect((nav : any) => {
			uni.createSelectorQuery().select('.TabsBox').boundingClientRect((tab : any) => {
				uni.createSelectorQuery().select('.bottomBox').boundingClientRect((btn : any) => {
					scrollViewHeight.value = windowHeight - nav.height - tab.height - btn.height;
				}).exec();
			}).exec();
		}).exec();


	}

	// 文件上传
	let uploadFile_list = ref<any>([]);
	// let uploadFile_action = mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/FileData/UploadSignleFile";

	const uploadFile_action = computed(() => {
		return mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/FileData/UploadSignleFile";
	})
	console.log(uploadFile_action.value);

	function beforeDelete({
		fileToDelete,
		uploadKey
	}, index : number, next : () => void) {

		uni.$utils.layer.confirm('确定要删除这个文件嘛？', {
			title: '提示信息',
		}, function ({ action }) {
			switch (action) {
				case 'confirm':
					uploadFile_list.value.splice(index, 1);
					// 模拟服务器接口
					setTimeout(() => {
						next();
					}, 300);
					break;
				case 'cancel':
					break;
				default:
					break;
			}
		})

	};
	function onSuccess(data : any) {
		let path = mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + data.data;
		console.log(path);
		uploadFile_list.value.push({
			path: path
		})
	};
	let ApprovalContent = ref("");

	let enabledSubmitBtn = ref(true);

	function openBaseScreen() {

	};

	// 转交
	function returnApproval() {
		let UserInfo = userStore.UserInfo;


		mainStore.openBaseScreen({
			allowClear: false, // 清除按钮
			cmd: 'getCkUserList', // 接口名
			titleName: "转交人员",
			listeningName: 'mFormApprove_Choice', // 监听器
			multiple: false, // 是否开启多选
			serverSearch: { // 查询项
				format: { // 数据映射
					displayValue: "UserName", // 显示值
					hiddenValue: "UserID", // 隐藏值
					pageIndex: "pageIndex", // 分页状态页码字段
					pageSize: "pageSize", // 分页状态每页数量字段
				},
				isLocal: false, // 是否启用本地数据
				localData: [], // 当开启本地数据时使用
				isPaging: false, //是否分页
				searchKey: '', //搜索关键词，应包含在param中
				subText: [{
					label: "描述", // label文本
					labelKey: "desc", // 显示label文本后文字的key
				}],
				disabled: { // 需要禁用的数据
					data: [UserInfo.UserID], // 基础数组形式
					key: "UserID", // 禁用的对应key
				},
				choiceData: [], // 选中数据
				choiceDataKey: "", // 选中数据的key
				isTree: false, // 是否开启树型下拉
			},
			param: { // 传递参数
			}
		})
	}
	// 拒绝 / 通过
	function dealApproval(approveType : number) {
		if (!enabledSubmitBtn.value) return;
		enabledSubmitBtn.value = false;

		uni.$utils.showLoading();
		let approveImgs = uploadFile_list.value.map((item : any) => {
			return item.path;
		});
		let obj = {
			ApprovalSort: BaseScreenParm.ApprovalSort, // 审批顺序
			Approve: approveType, // 通过/未通过
			KeyID: BaseScreenParm.keyValue,
			TableName: BaseScreenParm.globalData['physicalTableName'], // 物理表名
			Imgs: approveImgs.join(','), //
			ApprovalID: BaseScreenParm.ApprovalID, // 审批流ID

			ApprovalContent: ApprovalContent.value,
		};
		console.log(obj);
		request({
			config: {
			},
			url: 'Ck_ApprovalForm',
			method: 'POST',
			data: obj,
			success(ret : any) {
				console.log(ret);
				if (ret.status == 200) {
					if (ret.data.ds[0]['STATUS'] == 0) {
						//审批完成的脚本

						let workConfig = JSON.parse(BaseScreenParm.globalData['approvalConfig']).workConfig;
						if (ret.data.ds[0].isFinished == '1') {


							if (workConfig[2].script) {

								closeApprovePopup('doneConfirm', '2');

							} else {
								uni.$utils.msg('审批完成');

								closeApprovePopup('confirm');
							}


						} else {
							if (workConfig[1].script) {
								// let work = workConfig[2].script;
								closeApprovePopup('doneConfirm', '1');

							} else {
								uni.$utils.msg('审批完成');

								closeApprovePopup('confirm');
							}

						}

					} else {
						uni.$utils.msg(ret.data.ds[0]['msg'])
					}
				} else {
					uni.$utils.msg('请求失败，请重试')
				}
			}
		});

	}


	let popup_approve_form = reactive<any>({});


	function submitApprovePopup() {
		if (!enabledSubmitBtn.value) return;
		enabledSubmitBtn.value = false;
		let obj = {
			ApprovalSort: BaseScreenParm.ApprovalSort,
			KeyID: BaseScreenParm.keyValue,
			TableName: BaseScreenParm.globalData['physicalTableName'],
			returnUserID: popup_approve_form['UserID'],
			ApprovalID: BaseScreenParm.ApprovalID,
		}
		request({
			config: {
			},
			url: 'Ck_ReturnApproval',
			method: 'POST',
			data: obj,
			success(ret : any) {
				console.log(ret);
				if (ret.status == 200) {
					if (ret.data.ds[0]['STATUS'] == 0) {
						uni.$utils.msg("转交成功");

						setTimeout(() => {
							closeApprovePopup('confirm');
						}, 500);
					} else {
						uni.$utils.layer.alert(ret.data.ds[0]['msg']);
					}
				} else {
					uni.$utils.layer.alert('请求失败，请重试');
				}

			}
		})


	}


	const uToastRef = ref<any>(null);



	onMounted(() => {
		uni.$on("mFormApprove_Choice", function (ret) {
			console.log(ret);
			if (ret.titleName == '转交人员') {
				Object.assign(popup_approve_form, uni.$utils.deepClone(ret.data));


				setTimeout(() => {
					uni.$utils.layer.confirm('是否确认转交给' + ret.data.UserName, function (res : any) {
						switch (res.action) {
							case 'cancel':
								break;
							case 'confirm':
								submitApprovePopup()
								break;
							default:
								break;
						}
					})
				}, 0)

			}
		})


		nextTick(() => {
			setTimeout(() => {
				getScrollHeight();
			}, 500);
		});


	})

	onUnload(() => {
		uni.$off("mFormApprove_Choice");
		eventChannel.emit('cancel');
	})
</script>

<style lang="scss">
	// 顶部tab栏
	.TabsBox {
		padding: 10px 8px;
		background-color: #fff;
		border-bottom: 2px solid #eee;

		.u-tabs__wrapper__nav__item__text {
			padding: 4px 10px !important;
		}
	}

	.bottomBox {
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		height: 70px;
		line-height: 70px;
		padding: 6px 15px;
		// border-top: 1px solid #efefef;
		box-shadow: 1px 0 12px -9px #333;
		z-index: 99;

		.workBtn {
			border-color: #ddd !important;
			margin-left: 10px !important;

			&.small-font {
				font-size: 12px !important;
			}

			&:not(.small-font) {
				font-size: 14px;
			}
		}
	}


	// 转交
	.popup-content {
		position: relative;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		width: 86vw;
		max-width: 500px;
		padding: 40rpx 20px 30rpx;
		font-size: 12px;
		border-radius: 4px !important;
		overflow: hidden;

		&_close {
			position: absolute;
			top: 0;
			right: 0;
			width: 28px;
			height: 28px;
			font-weight: 600;
		}

		.title {
			font-size: 16px;
			font-weight: 600;
			text-align: center;
		}

		&_desc {
			margin: 24rpx 0;
			text-align: center;
			color: #999;
		}

		.check {
			zoom: .9;
			font-size: 13px;
			color: #999;
		}

		.btnBox {
			margin-top: 20px;

			.u-button {
				width: 44% !important;
			}
		}
	}
</style>